import sleep from '../sleep';

const {exec} = require('child_process');


const netWorkMana = {
    cache: null,
    monitoring: false,
    interrupt: false,
    decodeMessage(outStr: string) {
        const lines = outStr.replaceAll('\r', '').split('\n').filter(item => item);

        if (lines.length < 3) {
            return null;
        } else {
            lines.shift();
        }

        const headerList = lines[0].split(',').map((item) => item.split('Network ')[1]).filter((item) => item);
        const dateList = [];
        const speedList = [];
        for (let i = 1; i < lines.length; i++) {
            const lineStr = lines[i];
            const colItem = lineStr.replaceAll('"', '').split(',');
            const dateStr = colItem.shift();
            const speeds = colItem.map(item => Number(item));

            if (speeds.length === headerList.length) {
                dateList.push(dateStr);
                speedList.push(speeds);
            }
        }

        return {headerList, dateList, speedList};
    },
    async getNetworkList(sc: number = 20, onMessageFunc: Function) {
        return new Promise((resolve) => {
            // 网络适配器上发送和接收字节的速率
            const command = `chcp 65001 && typeperf -sc ${sc < 20 ? 20 : sc} "\\Network Interface(*)\\Bytes Sent/sec" "\\Network Interface(*)\\Bytes Received/sec`;
            const child = exec(command);


            let outStr = '';
            // 监听 stdout（标准输出）数据事件
            child.stdout.on('data', (data: string) => {
                outStr += data;
                const mes = this.decodeMessage(outStr);
                if (mes) {
                    onMessageFunc && onMessageFunc(this.decodeMessage(outStr));
                }

                if (this.interrupt) {
                    this.interrupt = false;
                    this.monitoring = false;
                    resolve(mes);
                }
            });

            // 监听 stderr（标准错误）数据事件
            child.stderr.on('data', (data: string) => {
                console.error(`标准错误: ${data}`);
            });

            // 监听子进程的 close 事件，获取退出码
            child.on('close', (code: string) => {
                resolve(this.decodeMessage(outStr));
            });
        });
    },
    async getRecently() {
        if (this.cache) {
            return this.cache;
        } else {
            // 监听十分钟
            this.openListen();
            await sleep(3000);
            return this.cache;
        }
    },
    openListen() {
        if (this.monitoring === false) {
            this.monitoring = true;
            this.getNetworkList(360, ((netWork: any) => {
                if (netWork?.dateList?.length < 100) {
                    this.cache = netWork;
                } else {
                    this.cache = {
                        headerList: netWork.headerList,
                        dateList: netWork.dateList.slice(-100),
                        speedList: netWork.speedList.slice(-100),
                    };
                }
            }));
        }
    },
    stopListen() {
        if (this.monitoring) {
            this.interrupt = false;
        }
        this.monitoring = false;
    }
};


export default netWorkMana;